import axios from "axios";
import { isDevEnv } from "../config/env";
import { trimParams } from ".";
const CancelToken = axios.CancelToken;
const httpMap = new Map();
function getHttpKey(config: any) {
  let { url, method, data, params } = config;
  data = isString(data) ? data : JSON.stringify(data);
  params = isString(params) ? params : JSON.stringify(params);
  return `url=${url}&method=${method}&data=${data}&params=${params}`;
}
function addHttp(config: any) {
  const httpKey = getHttpKey(config);
  if (httpMap.has(httpKey)) {
    const source = CancelToken.source();
    config.cancelToken = source.token;
    source.token.reason = {
      message: `【${config.url}】有相同请求未完成，请勿重复请求`,
    };
    source.cancel();
  } else {
    httpMap.set(httpKey, true);
  }
}
function removeHttp(config: any) {
  if (config) {
    const httpKey = getHttpKey(config);
    httpMap.delete(httpKey);
  }
}
// function clearHttp() {
//   httpMap.clear();
// }
const { VITE_PROXY_PATH, VITE_PROXY_TARGET } = import.meta.env;
const instance = axios.create({
  baseURL: isDevEnv ? VITE_PROXY_PATH : VITE_PROXY_TARGET,
  timeout: 1000 * 60 * 10,
  headers: {
    "Content-Type": "application/json",
  },
});
instance.interceptors.request.use(
  (config) => {
    config.params = trimParams(config.params);
    if (!isFormData(config.data)) {
      addHttp(config);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  (response) => {
    removeHttp(response.config);
    return response.data;
  },
  (error) => {
    removeHttp(error.config);
    return Promise.reject(error);
  }
);
instance.defaults.headers.common["Content-Type"] = "application/json";
export default instance;
